package org.example.thread.testCountDownLatch;

import com.alibaba.fastjson2.JSON;
import org.example.thread.testCompletableFuture.TodoItemsListRes;

import java.util.List;
import java.util.Map;
import java.util.concurrent.*;
import java.util.stream.Collectors;

/**
 * @author liyishan
 * @date 2024/3/6 10:08
 * @apiNote
 */

public class TestCountDownLatch {

    public static ThreadPoolExecutor threadPoolExecutor =
            new ThreadPoolExecutor(10,20, 0L,
                    TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(10));

    public static void main(String[] args) {
        List<TodoItemsListRes> todoItemsListResList = new CopyOnWriteArrayList<>();
        build(todoItemsListResList);
        Map<String, List<TodoItemsListRes>> toDoItemsMap = todoItemsListResList.stream().collect(Collectors.groupingBy(TodoItemsListRes::getBusinessId));
        final CountDownLatch countDownLatch = new CountDownLatch(toDoItemsMap.size());
        for(Map.Entry<String, List<TodoItemsListRes>> entry : toDoItemsMap.entrySet()){
            threadPoolExecutor.execute(() ->{
                try{
                    deal(entry.getValue());
                }catch (Exception e){
                    e.printStackTrace();
                }
                countDownLatch.countDown();
            });
        }
        try{
            countDownLatch.await();
            System.out.println(JSON.toJSON(todoItemsListResList));
        }catch (Exception e){
            e.printStackTrace();
        }
        threadPoolExecutor.shutdown();
    }

    public static void build(List<TodoItemsListRes> todoItemsListResList){
        for (int i = 0; i < 100; i++) {
            TodoItemsListRes todoItemsListRes = new TodoItemsListRes();
            todoItemsListRes.setId(i);
            todoItemsListRes.setBusinessId("name"+i);
            todoItemsListResList.add(todoItemsListRes);
        }
    }

    public static List<TodoItemsListRes> deal(List<TodoItemsListRes> todoItemsListResList){
        for (int i = 0; i < todoItemsListResList.size(); i++) {
            TodoItemsListRes todoItemsListRes = todoItemsListResList.get(i);
            todoItemsListRes.setDealStatus(i+1);
        }
        return todoItemsListResList;
    }
}
